package com.sunwhite.herostore.cmdhandler;

import com.sunwhite.herostore.entity.RankItem;
import com.sunwhite.herostore.msg.GameMsgProtocol;
import com.sunwhite.herostore.service.RankService;
import io.netty.channel.ChannelHandlerContext;

import java.util.Collections;

public class GetRankCmdHandler implements CmdHandler<GameMsgProtocol.GetRankCmd> {
    @Override
    public void handle(ChannelHandlerContext ctx, GameMsgProtocol.GetRankCmd msg) {
        if (null==ctx||msg==null){
            return;
        }

        //获取排行榜数据
        RankService.getInstance().getRank((rankItemList)->{
            if (null == rankItemList) {
                rankItemList = Collections.emptyList();
            }

            GameMsgProtocol.GetRankResult.Builder
                    resultBuilder = GameMsgProtocol.GetRankResult.newBuilder();

            for (RankItem rankItem : rankItemList) {
                GameMsgProtocol.GetRankResult.RankItem.Builder
                        rankItemBuilder = GameMsgProtocol.GetRankResult.RankItem.newBuilder();

                rankItemBuilder.setRankId(rankItem.rankId);
                rankItemBuilder.setUserId(rankItem.userId);
                rankItemBuilder.setUserName(rankItem.userName);
                rankItemBuilder.setHeroAvatar(rankItem.heroAvatar);
                rankItemBuilder.setWin(rankItem.win);

                resultBuilder.addRankItem(rankItemBuilder);
            }

            GameMsgProtocol.GetRankResult newResult = resultBuilder.build();
            ctx.writeAndFlush(newResult);
            return null;
        });
    }
}
